package com.example.demo01.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo01.config.EmpExcel;
import com.example.demo01.entity.Emp;
import com.example.demo01.entity.Result;
import com.example.demo01.entity.dto.EmpDto;
import com.example.demo01.entity.dto.ImportEmpDTO;
import com.example.demo01.entity.vo.EmpVo;
import com.example.demo01.mapper.EmpMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.alibaba.excel.EasyExcel;
import org.springframework.web.bind.annotation.GetMapping;

import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import com.alibaba.excel.EasyExcel;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 员工表 前端控制器
 * </p>
 *
 * @author 苏阳奕
 * @since 2025-06-10
 */
@RestController
@RequestMapping("/emp")
@Tag(name="员工管理")
public class EmpController {

    @Autowired
    private com.example.demo01.service.IEmpService empService;

    @Autowired
    private EmpMapper empMapper;

    @RequestMapping
    public Result<List<Emp>> getEmpList() {
        List<Emp> list = empService.list();
        return Result.success(list);
    }

    /**
     * 新增员工
     * @param emp
     * @return
     */
    @PostMapping
    public Result add(@RequestBody Emp emp) {
        boolean save = empService.save(emp);
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        if (save) {
            return Result.success(emp.getId());
        }
        return Result.fail("保存失败");

    }

    /**
     * 修改员工
     * @param emp
     * @return
     */
    @PutMapping
    public Result update(@RequestBody Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        boolean b = empService.updateById(emp);
        if (b)
            return Result.success();
        return Result.fail("修改员工失败，请稍后再试！");
    }

    /**
     * 删除员工
     * @param ids
     * @return
     */
    @DeleteMapping("/{ids}")
    public Result delete(@PathVariable List<Long> ids) {
        boolean b = empService.removeByIds(ids);
        if (b)
            return Result.success();
        return Result.fail("批量或者单个删除员工失败，请稍后再试！");
    }

    /**
     * 根据id查询员工
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result getById(@PathVariable Long id){
        return Result.success(empService.getById(id));
    }

    @GetMapping
    @Operation(summary = "分页查询",description = "分页查询信息")
    public Result page(EmpDto empDto){
        Page<Emp> page = new Page<>(empDto.getPage(),empDto.getPageSize());//分页
        LambdaQueryWrapper<Emp> wrapper = new LambdaQueryWrapper<>();
        if (empDto.getName()!=null && empDto.getName()!="")
            wrapper.like(Emp::getName,empDto.getName());//姓名
        if (empDto.getGender()!=null && empDto.getGender()!="")
            wrapper.eq(Emp::getGender,empDto.getGender());//性别
        if (empDto.getBegin()!=null && empDto.getBegin()!="")
            wrapper.ge(Emp::getEntrydate,empDto.getBegin());//开始时间
        if (empDto.getEnd()!=null && empDto.getEnd()!="")
            wrapper.le(Emp::getEntrydate,empDto.getEnd());//结束时间
        List<Emp> list = empService.list(page, wrapper);
        EmpVo empVo = new EmpVo();
        empVo.setRows(list);
        empVo.setTotal(page.getTotal()); // 设置总条数
        return Result.success(empVo);
    }


    /**
     * 导出 Excel
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        // 查询数据
        List<Emp> empList = empService.list();

        // 转换为 Excel 实体类
        List<EmpExcel> excelList = empList.stream().map(emp -> {
            EmpExcel excel = new EmpExcel();
            excel.setName(emp.getName());
            excel.setGender(emp.getGender() == 1 ? "男" : "女");
            excel.setEntrydate(emp.getEntrydate().toString());
            return excel;
        }).toList();

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        String fileName = URLEncoder.encode("员工列表", StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=UTF-8''" + fileName + ".xlsx");

        // 写出 Excel
        EasyExcel.write(response.getOutputStream(), EmpExcel.class)
                .autoCloseStream(true)
                .sheet("员工数据")
                .doWrite(excelList);
    }

    // 辅助方法：转换职位编号为名称
    private String getJobName(Integer jobId) {
        return switch (jobId) {
            case 1 -> "班主任";
            case 2 -> "讲师";
            case 3 -> "学工主管";
            case 4 -> "教研主管";
            default -> "未知职位";
        };
    }

/**
 * 导入 Excel 数据
 */
@PostMapping("/import")
@Operation(summary = "导入员工数据", description = "从 Excel 文件中导入员工信息")
public Result importExcel(@RequestParam("file") MultipartFile file) {
    try {
        ImportEmpDTO listener = new ImportEmpDTO();
        EasyExcel.read(file.getInputStream(), EmpExcel.class, listener).sheet().doRead();
        List<Emp> empList = listener.getEmpList();
        boolean save = empService.saveBatch(empList);
        if (save) {
            return Result.success("导入成功");
        } else {
            return Result.fail("导入失败");
        }
    } catch (Exception e) {
        e.printStackTrace();
        return Result.fail("文件读取异常：" + e.getMessage());
    }
}

}

